package cn.yunyichina.provider.hymed.service.neusoft;

import cn.yunyichina.provider.hymed.constant.NeusoftConst;
import cn.yunyichina.provider.hymed.model.bo.NeusoftRequestBO;
import cn.yunyichina.provider.hymed.model.bo.NeusoftResponseBO;
import cn.yunyichina.provider.hymed.util.HttpUtil;
import cn.yunyichina.provider.hymed.util.RsaUtil;
import cn.yunyichina.utils.commons.XmlUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Lullaby on 2017/10/20
 */
@Service
public class NeusoftServiceImpl extends NeusoftBaseService implements NeusoftService {

    private static final Logger logger = LoggerFactory.getLogger(NeusoftServiceImpl.class);

    @Override
    public <IN extends NeusoftRequestBO, OUT extends NeusoftResponseBO> OUT doExecute(IN in, Class<OUT> out) {
        try {
            Map map = JSON.parseObject(JSON.toJSONString(in), Map.class);//Dozer.convert(in, Map.class);
            String publicKey = (String) map.remove("publicKey");
            String privateKey = (String) map.remove("privateKey");

            String params = XmlUtils.buildMapXMLWithText(map, NeusoftConst.WEBSERVICE_XML_ROOT);
            logger.info("NeusoftServiceImpl.doExecute.params.before.encrypt -> {}", params);

            params = RsaUtil.encryptByPublicKey(params, publicKey);
            logger.info("NeusoftServiceImpl.doExecute.params.after.encrypt -> {}", params);

            String requestXml = getPrefixSoapHeader().concat(params).concat(getSuffixSoapHeader());
            logger.info("NeusoftServiceImpl.doExecute.requestXml -> {}", requestXml);

            String responseXml = HttpUtil.webservice(requestXml, getProperty(NeusoftConst.WEBSERVICE_URL));
            logger.info("NeusoftServiceImpl.doExecute.responseXml -> {}", responseXml);

            return getBusinessObject(responseXml, out, privateKey);
        } catch (Exception e) {
            logger.error("NeusoftServiceImpl.doExecute.IOException", e);
            return null;
        }
    }

}
